package http_proxy_middleware

import (
	"net/http/httputil"
	"sync"

	"gin-gateway/middleware"
	"gin-gateway/core/dao"
	"gin-gateway/reverse_proxy"
	"github.com/gin-gonic/gin"
)

var proxyPoolMap sync.Map

// HTTPReverseProxyMiddleware  反向代理+负载均衡
func HTTPReverseProxyMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		serviceDetail := GetServiceDetail(c)
		lb, err := dao.LoadBalancerManager.GetLoadBalancer(serviceDetail) // 负载均衡
		if err != nil {
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}

		trans, err := dao.TransporterManager.GetTrans(serviceDetail) // ReverseProxy Transporter 连接池
		if err != nil {
			middleware.ResponseError(c, 2003, err)
			c.Abort()
			return
		}

		proxy := reverse_proxy.NewLoadBalanceReverseProxy(c, lb, trans) // 负载均衡+反向代理
		proxy.ServeHTTP(c.Writer, c.Request)
		c.Abort()

		// proxy, ok := dao.Pool[serviceDetail.Info.ServiceName]
		// if !ok {
		// 	middleware.ResponseError(c, 2003, fmt.Errorf("get reverse pool fail"))
		// 	return
		// }
		// proxy.ServeHTTP(c.Writer, c.Request)
		// c.Abort()
	}
}

func getReverseProxy(c *gin.Context, serviceDetail *dao.ServiceDetail) *httputil.ReverseProxy {
	lb, err := dao.LoadBalancerManager.GetLoadBalancer(serviceDetail)
	if err != nil {
		return nil
	}
	// 连接池
	trans, err := dao.TransporterManager.GetTrans(serviceDetail)
	if err != nil {
		return nil
	}

	return reverse_proxy.NewLoadBalanceReverseProxy(c, lb, trans)
}

func getProxyPool(serviceDetail *dao.ServiceDetail) *sync.Pool {
	if val, ok := proxyPoolMap.Load(serviceDetail.Info.ServiceName); ok {
		return val.(*sync.Pool)
	}

	pool := &sync.Pool{
		New: func() any {
			return getReverseProxy(nil, serviceDetail)
		},
	}
	proxyPoolMap.Store(serviceDetail.Info.ServiceName, pool)

	return pool
}
